package com.tea.servlet;
import com.tea.entity.CartItem;
import com.tea.entity.Order;
import com.tea.entity.OrderItem;
import com.tea.entity.OrderItemDetail;
import com.tea.entity.User;
import com.tea.service.OrderService;
import com.tea.service.CartService;
import com.tea.service.impl.OrderServiceImpl;
import com.tea.service.impl.CartServiceImpl;
import com.tea.dao.OrderItemDao;
import com.tea.util.URLUtil;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet("/order")
public class OrderServlet extends HttpServlet {
    private final OrderService orderService = new OrderServiceImpl();
    private final CartService cartService = new CartServiceImpl();
    private final OrderItemDao orderItemDao = new OrderItemDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String action = req.getParameter("action");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        try {
            if (user == null) {
                String redirectUrl = URLUtil.buildRedirectUrl("/login.jsp", "msg", "请先登录");
                resp.sendRedirect(redirectUrl);
                return;
            }

            switch (action) {
                case "list":
                    handleOrderList(req, resp, user);
                    break;
                case "view":
                    handleOrderView(req, resp);
                    break;
                case "pay":
                    handlePaymentRedirect(req, resp);
                    break;
                default:
                    String redirectUrl = URLUtil.buildRedirectUrl("/error.jsp", "msg", "无效的操作");
                    resp.sendRedirect(redirectUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("errorMsg", "操作失败: " + e.getMessage());
            resp.sendRedirect("/error.jsp");
        }
    }

    private void handleOrderList(HttpServletRequest req, HttpServletResponse resp, User user) throws Exception {
        List<Order> orders = orderService.getOrdersByUserId(user.getId());
        req.setAttribute("orders", orders);
        req.getRequestDispatcher("/order-list.jsp").forward(req, resp);
    }

    private void handleOrderView(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String orderIdStr = req.getParameter("orderId");
        if (orderIdStr == null || orderIdStr.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少订单ID参数");
            return;
        }
        try {
            long orderId = Long.parseLong(orderIdStr);
            if (orderId <= 0) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的订单ID");
                return;
            }
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                req.setAttribute("errorMsg", "订单不存在");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
                return;
            }

            // 获取订单项详细信息
            List<OrderItemDetail> orderItems = orderItemDao.getOrderItemDetailsById(orderId);

            req.setAttribute("order", order);
            req.setAttribute("orderItems", orderItems);
            req.getRequestDispatcher("/order-detail.jsp").forward(req, resp);
        } catch (NumberFormatException e) {
            req.setAttribute("errorMsg", "无效的订单ID格式");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    private void handlePaymentRedirect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String orderId = req.getParameter("orderId");
        resp.sendRedirect("/payment?orderId=" + orderId);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String action = req.getParameter("action");
        HttpSession session = req.getSession();

        try {
            if ("create".equals(action)) {
                createOrder(req, resp);
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的操作类型");
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("errorMsg", "创建订单失败: " + e.getMessage());
            resp.sendRedirect("/cart.jsp");
        }
    }

    private void createOrder(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 实现订单创建逻辑，从购物车获取商品，调用OrderService创建订单
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            String redirectUrl = URLUtil.buildRedirectUrl("/login.jsp", "msg", "请先登录");
            resp.sendRedirect(redirectUrl);
            return;
        }

        // 从数据库重新获取最新购物车数据
        Map<Long, CartItem> cart = cartService.getUserCart(user.getId());
        if (cart == null || cart.isEmpty()) {
            session.setAttribute("errorMsg", "购物车为空，无法创建订单");
            resp.sendRedirect("/cart.jsp");
            return;
        }

        // 计算订单总金额
        double totalAmount = cartService.calculateTotalPrice(cart);

        // 调用Service层创建订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setStatus(0); // 待付款状态
        order.setTotalAmount(totalAmount);

        List<OrderItem> orderItems = cart.values().stream()
                .map(cartItem -> new OrderItem(null, null, cartItem.getProductId(), cartItem.getQuantity(), cartItem.getPrice() * cartItem.getQuantity()))
                .collect(Collectors.toList());

        String orderId = orderService.createOrder(order, orderItems);

        // 清空购物车（从数据库中清空）
        cartService.clearCart(user.getId());

        // 清空session中的购物车数据
        session.removeAttribute("cart");
        session.removeAttribute("totalPrice");

        // 重定向到订单详情页
        resp.sendRedirect("/order?action=view&orderId=" + orderId);
    }
}